package com.hup.joystick.service.joystick;

import com.hup.joystick.model.DeviceConfig;
import com.hup.joystick.model.KeyMapConfig;
import com.hup.joystick.model.joystick.AutoConnectConfig;
import com.hup.joystick.model.joystick.NativeEvent;
import com.hup.joystick.model.joystick.StandardEvent;
import com.hup.joystick.service.jna.EnumDeviceData;
import com.hup.utils.commons.io.BaseConfig.Path;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * {@link JoystickService#startAutoConnect(AutoConnectConfig, AutoConnectListener)}的回调类
 */
public interface AutoConnectListener extends JoyEventListener {

    default List<DeviceConfig> getConfig() {
        ArrayList<DeviceConfig> res = new ArrayList<>();
        File configDir = new File(Path.getBaseDir());
        File[] files = configDir.listFiles((dir, name) -> name.endsWith(DeviceConfig.EXT));
        if (files != null) {
            for (File file : files) {
                DeviceConfig data = DeviceConfig.loadFromFile(file);
                if (data != null && data.err == null) res.add(data);
            }
        }
        //res.clear();//test
        return res;
    }

    default DeviceConfig findDevice(List<EnumDeviceData> lstOnline, List<DeviceConfig> lstConfig) {
        for (EnumDeviceData online : lstOnline) {
            for (DeviceConfig config : lstConfig) {
                if (Objects.equals(online.tszInstanceName, config.name)
                        && Objects.equals(online.guid, config.guid)) {
                    return config;
                }
            }
        }
        return null;
    }

    @Override
    default boolean parseNativeEvent() {
        return false;
    }

    void onScanning();

    void beforeConnect(DeviceConfig deviceConfig);

    KeyMapConfig getKeyMapConfig();

    void onJoyEvent(NativeEvent none, StandardEvent e);

    /**
     * 发生了不可忽略的异常,会使[自动连接线程]停止;
     * 要重连设备,则要重新调用 {@link JoystickService#startAutoConnect(AutoConnectConfig, AutoConnectListener)}
     */
    void onException(Throwable e);

}